<template>
  <el-dialog
    v-model="isEditCrf"
    title="关联CRF设置"
    width="800"
    custom-class="edit-crf-dialog"
    modal-class="m-edit-crf-dialog"
  >
    <el-row :gutter="20">
      <el-col :span="9">
        <span>CRF名称：</span>
        <el-input v-model="crfSearch.name" style="width: 200px" placeholder="请输入CRF名称" />
      </el-col>
      <el-col :span="10">
        <span>类 型：</span>
        <el-select
          v-model="crfSearch.lbType"
          placeholder="请选择类型"
          filterable
          clearable
          style="width: 200px"
        >
          <el-option
            v-for="item in crfSelectOptions"
            :key="item.value"
            :label="item.dictValue"
            :value="item.dictKey"
          />
        </el-select>
      </el-col>
      <el-col :span="5">
        <el-button type="primary" @click="handleEditCrfSearch(0)">搜 索</el-button>
        <el-button @click="handleEditCrfSearch(1)">清 空</el-button>
      </el-col>
    </el-row>

    <div class="selected-content">
      <avue-crud :data="selectedData" :option="crfOption" :table-loading="selectedLoading">
        <template #menu-left>
          <div class="table-hint">已选CRF：</div>
        </template>
        <template #menu="{ row, index, size }">
          <el-button
            type="danger"
            :size="size"
            icon="el-icon-delete"
            @click="handleSelectedDel(row, index)"
            >删 除</el-button
          >
        </template>
      </avue-crud>
      <div class="selected-footer">
        <span style="color: red; font-size: 14px; flex: 1"
          >点击“确定”后点击“提交”才可保存已选CRF</span
        >
        <el-button type="primary" @click="handleEditCrfConfirm">确 定</el-button>
      </div>
    </div>

    <avue-crud
      :data="unselectedData"
      :option="crfOption"
      v-model:page="page"
      :table-loading="loading"
      @current-change="currentChange"
      @size-change="sizeChange"
    >
      <template #menu-left>
        <div class="table-hint">未选CRF：</div>
      </template>
      <template #menu="{ row, index, size }">
        <el-button type="danger" :size="size" @click="handleSelected(row, index)">选 中</el-button>
      </template>
    </avue-crud>
  </el-dialog>
</template>
<script setup>
import {
  getList,
  getDetail,
  add,
  update,
  remove,
  toShare,
  remark,
  lock,
  copy,
} from '@/api/crf/crf';
import { getDictionary } from '@/api/system/dictbiz';
import { ref, reactive, computed, onMounted, defineEmits, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import { useStore } from 'vuex';
const route = useRoute();
const store = useStore();
const emit = defineEmits();
let crfSearch = reactive({
  name: null,
  lbType: null,
});
let crfSelectOptions = ref([]);
let isEditCrf = ref(false);
let sendData = ref({});
const crfOption = ref({
  index: true,
  indexWidth: 80,
  indexLabel: '编号',
  // height: '300',
  height: 'auto',
  calcHeight: 500,
  maxHeight: 300,
  selection: false,
  addBtn: false,
  editBtn: false,
  viewBtn: false,
  delBtn: false,
  menuWidth: 100,
  align: 'center',
  column: [
    // {
    //   label: '编号',
    //   prop: 'codeNumber',
    //   type: 'input',
    //   overHidden: true,
    // },
    {
      label: 'CRF名称',
      prop: 'name',
      type: 'input',
      overHidden: true,
    },
    // {
    //   label: '可识别',
    //   prop: 'isType',
    //   type: 'select',
    //   dicData: [
    //     {
    //       label: '否',
    //       value: 0,
    //     },
    //     {
    //       label: '是',
    //       value: 1,
    //     },
    //   ],
    //   overHidden: true,
    // },
    {
      label: '创建者',
      prop: 'createUser',
      type: 'select',
      dicUrl: `/blade-system/user/user-list`,
      props: {
        label: 'realName',
        value: 'id',
      },
      filterable: true,
      overHidden: true,
    },
  ],
});
const selectedData = ref([]);
const unselectedData = ref([
  {
    codeNumber: '24486',
    name: '77',
    isType: 0,
    createUser: '1123598821738675201',
    id: 1,
  },
  {
    codeNumber: '23708',
    name: '移植后+360天+-7天',
    isType: 0,
    createUser: '1123598821738675201',
    id: 2,
  },
  {
    codeNumber: '23707',
    name: '移植后+100天+-7天',
    isType: 0,
    createUser: '1123598821738675201',
    id: 3,
  },
  {
    codeNumber: '23325',
    name: '广泛性焦虑障碍量表（GAD-7）',
    isType: 0,
    createUser: '1123598821738675201',
    id: 4,
  },
]);
let loading = ref(false);
let selectedLoading = ref(false);
const page = ref({
  pageSize: 10,
  currentPage: 1,
  total: 0,
});
const userInfo = computed(() => store.getters.userInfo);
const open = val => {
  console.log('接收数据', val);
  isEditCrf.value = val.isOpen;
  sendData.value = val;
  initData();
};
const initData = async () => {
  selectedData.value = [];
  page.value.currentPage = 1;
  let res = await getDictionary({
    code: 'scale_type',
  });
  crfSelectOptions.value = res.data.data;
  onLoad(page.value);
};
// 搜索清空点击事件
// 0:搜索，1:清空
const handleEditCrfSearch = type => {
  if (type === 0) {
    onLoad(page.value, crfSearch, 1);
  } else {
    crfSearch.name = null;
    crfSearch.lbType = null;
    onLoad(page.value, crfSearch, 1);
  }
};
// 删除点击事件
const handleSelectedDel = (row, index) => {
  selectedData.value.splice(index, 1);
};
// 选中点击事件
const handleSelected = (row, index) => {
  const exists = selectedData.value.some(item => item.id === row.id);
  if (exists) {
    ElMessage.error('该CRF已选择！');
    return;
  }
  selectedData.value.push(row);
  // unselectedData.value.splice(index, 1);
};
// 确定点击事件
const handleEditCrfConfirm = () => {
  isEditCrf.value = false;
  emit('changeCrfList', selectedData.value);
};
const currentChange = currentPage => {
  page.value.currentPage = currentPage;
  onLoad(page.value, crfSearch, 1);
  // TabRefreshChange();
};
const sizeChange = pageSize => {
  page.value.pageSize = pageSize;
  onLoad(page.value, crfSearch, 1);
  // TabRefreshChange();
};
const onLoad = (page, params = {}, isMerge = null) => {
  loading.value = true;
  selectedLoading.value = true;
  let values = {
    descs: 'create_time',
    create_user: userInfo.value.user_id,
    ...params,
  };
  getList(page.currentPage, page.pageSize, values).then(res => {
    const DATA = res.data.data;
    page.total = DATA.total;
    unselectedData.value = DATA.records;
    let newData = [...DATA.records];
    loading.value = false;
    if (sendData.value.crfList.length != 0 && isMerge != 1) {
      initGetList(newData, DATA.total);
      // const result = sendData.value.crfList
      //   .map(item1 => {
      //     // 在 array2 中查找 id 相同的对象
      //     const match = newData.find(item2 => item2.id === item1.crf);
      //     return match || null; // 如果没有匹配的返回 null
      //   })
      //   .filter(item => item !== null); // 过滤掉 null
      //   setTimeout(() => {
      //     selectedData.value = [...result];
      //   },0)

      // selectedData.value = [];
      // const result = sendData.value.crfList
      //   .map(item1 => {
      //     // 在 array2 中查找 id 相同的对象
      //     let match = null;
      //     if (item1.crf) {
      //       match = newData.find(item2 => item2.id === item1.crf);
      //     } else {
      //       match = newData.find(item2 => item2.id === item1.id);
      //     }
      //     if (match) {
      //       // 返回合并后的对象
      //       return { ...item1, ...match };
      //     }
      //     return null; // 如果没有匹配的，返回 null
      //   })
      //   .filter(item => item !== null); // 过滤掉 null
      // setTimeout(() => {
      //   selectedData.value = [...result];
      //   console.log('这里的数据', selectedData.value);
      // }, 0);
    } else {
      selectedLoading.value = false;
    }
    // selectionClear();
  });
};
const initGetList = (newData, total) => {
  let values = {
    descs: 'create_time',
    create_user: userInfo.value.user_id,
  };
  getList(1, total, values).then(res => {
    const DATA = res.data.data;
    let newData = [...DATA.records];
    const result = sendData.value.crfList
      .map(item1 => {
        // 在 array2 中查找 id 相同的对象
        let match = null;
        if (item1.crf) {
          match = newData.find(item2 => item2.id === item1.crf);
        } else {
          match = newData.find(item2 => item2.id === item1.id);
        }
        if (match) {
          // 返回合并后的对象
          return { ...item1, ...match };
        }
        return null; // 如果没有匹配的，返回 null
      })
      .filter(item => item !== null); // 过滤掉 null
    setTimeout(() => {
      selectedData.value = [...result];
      selectedLoading.value = false;
      // console.log('这里的数据', selectedData.value);
    }, 0);
  });
};
defineExpose({
  open,
});
</script>
<style scoped lang="scss">
.edit-crf-content {
  width: 90%;
  height: 100%;
}
.selected-content {
  width: 100%;
  height: auto;
  padding: 10px 0;
  margin: 20px 0;
  border-top: 3px solid #00c0ef;
  border-bottom: 3px solid #00c0ef;
}
.table-hint {
  height: 100%;
  color: black;
  font-size: 16px;
  font-weight: 550;
  display: flex;
  align-items: center;
}
.selected-footer {
  width: 100%;
  height: auto;
  margin: 5px 0;
  display: flex;
  align-items: center;
}
.m-edit-crf-dialog {
  ::v-deep .el-overlay-dialog {
    overflow: hidden !important;
  }
}
</style>